import { Injectable, NotFoundException } from '@nestjs/common';
import { UpdateFilmFileRelationalDto } from './dto/update-film_file_relational.dto';
import { CreateFilmFileRelationalDto } from './dto/create-film_file_relational.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { FilmFileRelational } from './entities/film_file_relational.entity';
import { FileListService } from 'src/file-list/file-list.service';
import { Repository } from 'typeorm';

@Injectable()
export class FilmFileRelationalService {
  constructor(
    @InjectRepository(FilmFileRelational)
    private readonly filmFileRelationalRepository: Repository<FilmFileRelational>,
    private readonly fileListService: FileListService,
  ) {}
  async create(createFilmFileRelationalDto: CreateFilmFileRelationalDto) {
    const searchRes = await this.filmFileRelationalRepository.findOne({
      where: {
        film_id: createFilmFileRelationalDto.film_id,
        file_id: createFilmFileRelationalDto.file_id,
      },
    });
    if (searchRes) {
      return '已经添加';
    } else {
      const sceneFileRelational = this.filmFileRelationalRepository.create(
        createFilmFileRelationalDto,
      );
      this.filmFileRelationalRepository.insert(sceneFileRelational);
    }
  }
  findAll() {
    return this.filmFileRelationalRepository.find();
  }
  findOne(id: string) {
    return this.filmFileRelationalRepository.findOne({ where: { id: id } });
  }
  async getFileTypeByFilmId(film_id: string, file_type: string) {
    const fileList = await this.filmFileRelationalRepository.find({
      where: { film_id: film_id },
      select: ['file_id', 'used', 'id'],
    });
    if (fileList.length === 0) {
      return [];
    }
    const fileIdList = fileList.map((item) => item.file_id);
    let fileTypeList: any = await this.fileListService.getByTypeAndFileIds(
      file_type,
      fileIdList,
    );
    // 合并used字段到fileTypeList
    fileTypeList = fileTypeList.map((file) => {
      // 查找file对应的used值
      const foundFile = fileList.find((item) => item.file_id === file.id);
      return {
        ...file,
        used: foundFile ? foundFile.used : false, // 如果没有找到，默认used为false
        scenceToFileId: foundFile ? foundFile.id : '',
      };
    });
    return fileTypeList;
  }
  async updateFilmToFileRelationItem(
    id: string,
    updateFilmFileRelationalDto: UpdateFilmFileRelationalDto,
  ) {
    const oldItem = await this.filmFileRelationalRepository.findOne({
      where: { id },
    });

    if (!oldItem) {
      throw new NotFoundException('该修改对象不存在');
    }

    const updateSceneFileRelational = this.filmFileRelationalRepository.merge(
      oldItem,
      updateFilmFileRelationalDto,
    );

    await this.filmFileRelationalRepository.save(updateSceneFileRelational);

    // 返回更新后的实体或其他有用的信息
    return updateSceneFileRelational;
  }
  async remove(id: string) {
    const result = await this.filmFileRelationalRepository.delete({
      id: id,
    });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }
  async removeRelationByFileId(fileId: string) {
    const result = await this.filmFileRelationalRepository.delete({
      file_id: fileId,
    });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }

  async removeByFilmId(filmId: string) {
    const result = await this.filmFileRelationalRepository.delete({
      film_id: filmId,
    });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }

  async getFilesIsUsedByFilm(param: any) {
    const fileList = await this.filmFileRelationalRepository.find({
      where: { film_id: param.filmId },
      select: ['file_id', 'used', 'id'],
    });
    param.filesArray = param.filesArray.map((file) => {
      const foundFile = fileList.find((item) => item.file_id === file.id);
      return {
        ...file,
        used: foundFile ? foundFile.used : false, // 如果没有找到，默认used为false
        scenceToFileId: foundFile ? foundFile.id : '',
      };
    });
    return param.filesArray;
  }
  async updateFilmToFileRelationItemByFileIdFilmId(
    updateFilmFileRelationalDto: UpdateFilmFileRelationalDto,
  ) {
    const oldItem = await this.filmFileRelationalRepository.findOne({
      where: {
        film_id: updateFilmFileRelationalDto.film_id,
        file_id: updateFilmFileRelationalDto.file_id,
      },
    });
    if (!oldItem) {
      throw new NotFoundException('该修改对象不存在');
    }

    const updateSceneFileRelational = this.filmFileRelationalRepository.merge(
      oldItem,
      updateFilmFileRelationalDto,
    );

    await this.filmFileRelationalRepository.save(updateSceneFileRelational);

    // 返回更新后的实体或其他有用的信息
    return updateSceneFileRelational;
  }
  getFilmToFileRelationItemByFileIdFilmId(param: {
    file_id: string;
    film_id: string;
  }) {
    return this.filmFileRelationalRepository.findOne({
      where: { file_id: param.file_id, film_id: param.film_id },
    });
  }
  async getIsUsedByFileId(fileuuid: string) {
    const findRes = await this.filmFileRelationalRepository.find({
      where: { file_id: fileuuid },
    });
    // 检查 findRes 数组中是否至少有一个对象的 used 属性为 true
    return await findRes.some((item) => item.used === true);
  }
}
